<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="bg-decoration"></div>

    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 标题区域 -->
      <div class="login-header">
        <img src="@/assets/logo.png" alt="农村爱心水果售卖系统logo" class="logo">
        <h1 class="title">农村爱心水果售卖系统</h1>
        <p class="subtitle">请选择登录类型并输入账号信息</p>
      </div>

      <!-- 登录类型切换 -->
      <div class="login-type-tabs">
        <div
            class="tab-item"
            :class="{ active: loginType === 'user' }"
            @click="loginType = 'user'"
        >
          <el-icon class="tab-icon"><User /></el-icon>
          <span>用户登录</span>
        </div>
        <div
            class="tab-item"
            :class="{ active: loginType === 'admin' }"
            @click="loginType = 'admin'"
        >
          <el-icon class="tab-icon"><Setting /></el-icon>
          <span>管理员登录</span>
        </div>
      </div>

      <!-- 登录表单 -->
      <el-form
          :model="loginForm"
          ref="loginFormRef"
          :rules="loginRules"
          class="login-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              autocomplete="off"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <!-- 管理员登录额外字段 -->
        <el-form-item
            prop="verifyCode"
            v-if="loginType === 'admin'"
        >
          <el-input
              v-model="loginForm.verifyCode"
              placeholder="请输入验证码"
              prefix-icon="Key"
              class="verify-code-input"
          />
          <div class="verify-code-img" @click="refreshVerifyCode">
            <span>{{ verifyCode }}</span>
          </div>
        </el-form-item>

<!--        <el-form-item class="form-actions">-->
<!--          <el-checkbox v-model="loginForm.rememberMe" class="remember-me">-->
<!--            记住我-->
<!--          </el-checkbox>-->
<!--          <el-link type="primary" class="forgot-password">-->
<!--            忘记密码?-->
<!--          </el-link>-->
<!--        </el-form-item>-->

        <el-button
            type="primary"
            class="login-btn"
            @click="handleLogin"
            :loading="loading"
        >
          登录
        </el-button>

        <!-- 用户注册入口（仅用户登录显示） -->
        <div class="register-link" v-if="loginType === 'user'">
          还没有账号?
          <el-link type="primary" @click="goToRegister">
            立即注册
          </el-link>
        </div>
      </el-form>
    </div>

    <!-- 页脚 -->
    <footer class="login-footer">
      © 2025 农村爱心水果管理系统 版权所有
    </footer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { User, Setting, Lock, Key } from '@element-plus/icons-vue';
import loginApi from '@/api/login_api.js'; // 登录接口

// 路由实例
const router = useRouter();

// 登录类型（user/admin）
const loginType = ref('user');

// 加载状态
const loading = ref(false);

// 表单引用
const loginFormRef = ref(null);

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  verifyCode: '',
  rememberMe: false
});

// 验证码
const verifyCode = ref('');

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为 4 个字符', trigger: 'blur' }
  ]
};

// 生成随机验证码
const generateVerifyCode = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let code = '';
  for (let i = 0; i < 4; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
};

// 刷新验证码
const refreshVerifyCode = () => {
  verifyCode.value = generateVerifyCode();
};

const handleLogin = async () => {
  // 表单验证等前置逻辑...

  //调用后端登录API
  loading.value = true;
  try {
    const loginVO = await loginApi.login({
      username: loginForm.username,
      password: loginForm.password,
      type: loginType.value,//传给后端的登录类型
    });

// loginVO 就是 data.data
    const token = loginVO?.token;
    if (!token) throw new Error('未从响应中获取到 token');

// 将 Token 存储在 localStorage
    localStorage.setItem('token', token);
    // 存储用户信息
    const userInfo = {
      username: loginForm.username,
      role: loginVO?.role,  // 后台返回了用户角色信息
    };
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
    console.log("121212",localStorage.setItem('userInfo', JSON.stringify(userInfo)))

// 记住我
    if (loginForm.rememberMe) {
      localStorage.setItem('username', loginForm.username);
      localStorage.setItem('password', loginForm.password);
    } else {
      localStorage.removeItem('username');
      localStorage.removeItem('password');
    }

// 再拉取当前用户或跳转
// const me = await loginApi.getCurrentUser();
    //跳转首页
    router.push('/');

    // 登录成功处理...
  } catch (error) {
    // 仅保留一个catch块
    console.error('登录失败详情:', error);
    // 错误提示已由request.js统一处理，此处无需重复提示
  } finally {
    // 仅保留一个finally块
    loading.value = false;
  }
};
// 前往注册页面
const goToRegister = () => {
  router.push('/register');
};

// 初始化
onMounted(() => {
  // 生成初始验证码
  refreshVerifyCode();

  // 读取记住的账号密码
  const savedUsername = localStorage.getItem('username');
  const savedPassword = localStorage.getItem('password');
  if (savedUsername && savedPassword) {
    loginForm.username = savedUsername;
    loginForm.password = savedPassword;
    loginForm.rememberMe = true;
  }
}

);
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f0f9f0;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image:
      radial-gradient(circle at 20% 30%, rgba(46, 125, 50, 0.05) 0%, transparent 40%),
      radial-gradient(circle at 80% 70%, rgba(46, 125, 50, 0.05) 0%, transparent 40%);
  z-index: 0;
}

/* 登录卡片 */
.login-card {
  width: 100%;
  max-width: 420px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 30px;
  z-index: 1;
  transition: transform 0.3s ease;
}

.login-card:hover {
  transform: translateY(-5px);
}

/* 标题区域 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  height: 60px;
  margin-bottom: 15px;
  object-fit: contain;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #2e7d32;
  margin-bottom: 8px;
}

.subtitle {
  color: #666;
  font-size: 14px;
}

/* 登录类型切换 */
.login-type-tabs {
  display: flex;
  margin-bottom: 25px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
}

.tab-item {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 15px;
}

.tab-item.active {
  background-color: #2e7d32;
  color: white;
  font-weight: 500;
}

.tab-item:not(.active):hover {
  background-color: #f9fafb;
}

.tab-icon {
  font-size: 18px;
}

/* 登录表单 */
.login-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.verify-code-container {
  display: flex;
  gap: 10px;
}

.verify-code-input {
  flex: 1;
}

.verify-code-img {
  width: 120px;
  height: 40px;
  background-color: #f0f9f0;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  letter-spacing: 4px;
  cursor: pointer;
  user-select: none;
  color: #2e7d32;
  border: 1px solid #dcdfe6;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.remember-me {
  color: #666;
}

.forgot-password {
  font-size: 14px;
}

.login-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  background-color: #2e7d32;
  border-color: #2e7d32;
}

.login-btn:hover {
  background-color: #1b5e20;
  border-color: #1b5e20;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

/* 页脚 */
.login-footer {
  margin-top: 30px;
  color: #999;
  font-size: 12px;
  text-align: center;
  z-index: 1;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .login-card {
    margin: 0 20px;
    padding: 25px 20px;
  }

  .title {
    font-size: 22px;
  }
}
</style>
